function mySetInterval(fn, timeout) {
  let timer = {
    flag: true,
  };

  function interval() {
    if (timer.flag) {
      fn();
      setTimeout(interval, timeout);
    }
  }

  setTimeout(interval, timeout);
  return timer;
}

function foo() {
  console.log("foo");
}

let res = mySetInterval(foo, 1000);

setTimeout(() => {
  res.flag = false;
}, 5000);
